package com.aiatomic.countlib;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;

import java.util.ArrayList;
import java.util.List;

public class App extends Application {
    List<Activity> activities = new ArrayList<>();
    @Override
    public void onCreate() {
        super.onCreate();
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                activities.add(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {

            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                activities.remove(activity);
            }
        });
        Thread.UncaughtExceptionHandler handler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(handler));
    }

    class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
        Thread.UncaughtExceptionHandler mDefault;

        public MyExceptionHandler(Thread.UncaughtExceptionHandler mDefault) {
            this.mDefault = mDefault;
        }

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            Activity activity = activities.get(0);
            Intent intent = new Intent(activity,activity.getClass());
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(intent);
            activity.finish();
            Process.killProcess(Process.myPid());
            System.exit(10);
        }
    }
}
